#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'

void solve() {
	int n; cin >> n;
	priority_queue<int> pq;
	ll ans = 0;
	for (int i = 1; i <= n; i++) {
		ll x; cin >> x;
		if (x == 0 && pq.size()) {
			ans += pq.top();
			pq.pop();
		}
		else pq.push(x);
	}
	cout << ans << endl;
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int t; cin >> t;
	while (t--) {
		solve();
	}
	return 0;
}